package com.pm.web.controller.buglist;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pm.buglist.domain.Bugs;
import com.pm.buglist.domain.Project;
import com.pm.buglist.service.ProjectService;
import com.pm.buglist.service.SysFilesService;
import com.pm.common.annotation.Log;
import com.pm.common.core.controller.BaseController;
import com.pm.common.core.domain.AjaxResult;
import com.pm.common.core.page.TableDataInfo;
import com.pm.common.enums.BusinessType;
import com.pm.common.enums.FileType;
import com.pm.common.utils.SecurityUtils;
import com.pm.common.utils.poi.ExcelUtil;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * <p>
 * 项目信息表 前端控制器
 * </p>
 *
 * @author wwm
 * @since 2023-12-14
 */
@Slf4j
@RestController
@RequestMapping("/business/project")
public class ProjectController extends BaseController {

    @Resource
    private ProjectService projectService;

    @Resource
    private SysFilesService sysFilesService;

    @GetMapping("/list")
    public TableDataInfo projectList(Project project){
        startPage();
        List<Project> projectList = projectService.getProjectList(project);
        return getDataTable(projectList);
    }




    @GetMapping("/ProjectList")
    public AjaxResult getProjectList(){
        QueryWrapper<Project> wrapper = new QueryWrapper<>();
        wrapper.eq("del_flag","0");
        wrapper.eq("status",10);
        List<Project> list = projectService.list(wrapper);
        return AjaxResult.success(list);
    }

    @Log(title = "项目管理:新增", businessType = BusinessType.INSERT)
    @PreAuthorize("@ss.hasPermi('business:project:add')")
    @PostMapping("/add")
    public AjaxResult addProject(@RequestBody Project project){
        return projectService.insertProject(project);
    }

    @Log(title = "项目管理:修改", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('business:project:update')")
    @PostMapping("/update")
    public AjaxResult upProject(@RequestBody Project project){
        return projectService.updateProject(project);
    }

    @GetMapping("/getProject/{id}")
    public AjaxResult getProject(@PathVariable("id") Long id){
        return projectService.getProjectById(id);
    }

    @Log(title = "项目管理:删除",businessType = BusinessType.DELETE)
    @PreAuthorize("@ss.hasPermi('business:project:delete')")
    @GetMapping("/delete/{id}")
    public AjaxResult delProject(@PathVariable("id") Long id){
        return projectService.delProject(id);
    }

    @Log(title = "项目管理:取消",businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('business:project:cancel')")
    @GetMapping("/cancel/{id}")
    public AjaxResult cancelProject(@PathVariable("id") Long id){
        return projectService.cancelProjectById(id);
    }

    /**
     * 导出项目数据
     */
    @PreAuthorize("@ss.hasPermi('business:project:export')")
    @Log(title = "导出项目数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Project project)
    {
        List<Project> list = projectService.getProjectList(project);
        ExcelUtil<Project> util = new ExcelUtil<Project>(Project.class);
        util.exportExcel(response, list, "项目数据");
    }

    @PreAuthorize("@ss.hasPermi('business:project:close')")
    @Log(title = "项目管理:关闭项目",businessType = BusinessType.UPDATE)
    @GetMapping("/close/{id}")
    public AjaxResult closeProject(@PathVariable("id") Long id){
        return projectService.closeProjectById(id);
    }

    @PreAuthorize("@ss.hasPermi('business:project:import')")
    @Log(title = "项目管理:导入项目及bugList",businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public AjaxResult importProjectBugList(MultipartFile file) throws IOException {

        //获取用户id
        Long userId = SecurityUtils.getUserId();

        @Cleanup
        InputStream inputStream = file.getInputStream();
        Workbook excelWorkBook = ExcelUtil.getExcelWorkBook(inputStream);

        // 2. 创建 Sheet 对象
        Sheet sheet = excelWorkBook.getSheetAt(0);
        //存储整个excel 表格数据
        List<Map<Project,List<Bugs>>> excelDate=new ArrayList<>();
        Integer rowIndex=1;//从第二行开始读
        Integer maxProjectLength=13;
        boolean flag=true;
        Map<Project,List<Bugs>> map=null;
        List<Bugs> list=null;
        Project project =new Project();
        while (flag){//循环读取
            if(ObjectUtils.isEmpty(sheet.getRow(rowIndex))){
                //只有一个项目bug数据
                map.put(project,list);
                excelDate.add(map);
                flag=false;
                break;
            }
            String s = sheet.getRow(rowIndex).getCell(0).toString();

            if(!StringUtils.isEmpty(s) && s.equals("项目编码")){
                //进来之后证明一个项目数据读取完毕
                if(!ObjectUtils.isEmpty(project)&& !CollectionUtils.isEmpty(list)){//都不为空，添加
                    map.put(project,list);
                    excelDate.add(map);
                }
                map=new HashMap<>();//进来之后就是一个新的map
                list=new ArrayList<>();//进来之后是一个新的list
                project=new Project();//进来之后是一个新的project
                //TODO 读取项目数据
                for (int i = 0; i < 3; i++) {
                    if(i==0){//项目第一行
                        for (Integer integer = 2; integer < maxProjectLength; integer+=4) {
                            String Pvalue = sheet.getRow(rowIndex).getCell(integer).toString();
                            switch (integer){
                                case 2:
                                    if(StringUtils.isEmpty(Pvalue)){
                                        flag=false;
                                        return AjaxResult.error("第"+rowIndex+"行的项目编码不能为空");
                                    }
                                    project.setProjectNo(Pvalue);//项目编码
                                    break;
                                case 6:
                                    project.setCustom(Pvalue);//客户
                                    break;
                                case 10:
                                    if(StringUtils.isEmpty(Pvalue)){
                                        flag=false;
                                        return AjaxResult.error("第"+rowIndex+"行的机型不能为空");
                                    }
                                    project.setModel(Pvalue);//机型
                                    break;
                                default:
                                    break;
                            }
                        }
                    }else if(i==1){//项目第二行
                        for (Integer integer = 2; integer < maxProjectLength; integer+=4) {
                            String Pvalue = sheet.getRow(rowIndex).getCell(integer).toString();
                            switch (integer){
                                case 2:
                                    if(StringUtils.isEmpty(Pvalue)){
                                        flag=false;
                                        return AjaxResult.error("第"+rowIndex+"行的专案类别不能为空");
                                    }
                                    project.setLevel(Pvalue);//专案类别
                                    break;
                                case 6:
                                    if(StringUtils.isEmpty(Pvalue)){
                                        flag=false;
                                        return AjaxResult.error("第"+rowIndex+"行的AD板不能为空");
                                    }
                                    project.setAdBoard(Pvalue);//AD板
                                    break;
                                case 10:
                                    if(StringUtils.isEmpty(Pvalue)){
                                        flag=false;
                                        return AjaxResult.error("第"+rowIndex+"行的芯片组不能为空");
                                    }
                                    project.setChipGroup(Pvalue);//芯片组
                                    break;
                                default:
                                    break;
                            }
                        }
                    }else if(i==2){//项目第三行
                        for (Integer integer = 2; integer < maxProjectLength; integer+=4) {
                            String Pvalue = sheet.getRow(rowIndex).getCell(integer).toString();
                            switch (integer){
                                case 2:
                                    if(StringUtils.isEmpty(Pvalue)){
                                        flag=false;
                                        return AjaxResult.error("第"+rowIndex+"行的LCM/OC不能为空");
                                    }
                                    project.setLcmOc(Pvalue);//LCM/OC
                                    break;
                                case 6:
                                    if(StringUtils.isEmpty(Pvalue)){
                                        flag=false;
                                        return AjaxResult.error("第"+rowIndex+"行的电源/适配器不能为空");
                                    }
                                    project.setPowerSupply(Pvalue);//电源/适配器
                                    break;
                                case 10:
//                                    if(StringUtils.isEmpty(Pvalue)){
//                                        return AjaxResult.error("第"+rowIndex+"行的机型不能为空");
//                                    }
                                    project.setCurrentBoard(Pvalue);//恒流板
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                    //读取完跳行
                    rowIndex++;
                }

            }else {
                //读取对应的bugs信息
                if(!StringUtils.isEmpty(s) && s.equals("问题类别")){
                    rowIndex++;//跳过bugs标题行
                }else {//为空、不为空/不是问题类别
                    if(!StringUtils.isEmpty(s)){
                        //TODO 开始读取对应项目的bug
                        Bugs bugs = new Bugs();
                        for (int i = 0; i < 13; i++) {
                            String Bvalue = sheet.getRow(rowIndex).getCell(i).toString();
                            switch (i){
                                case 0:
                                    if(StringUtils.isEmpty(Bvalue)){
                                        return AjaxResult.error("第"+rowIndex+"行的问题类别不能为空");
                                    }
                                    bugs.setProblemType(Bvalue);
                                    break;
                                case 1:
                                    if(StringUtils.isEmpty(Bvalue)){
                                        return AjaxResult.error("第"+rowIndex+"行的提报日期不能为空");
                                    }
                                    try {
                                        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
                                        Date dlDate = dateFormat.parse(Bvalue);
                                        Instant instant = dlDate.toInstant(); // 将Date对象转换为Instant对象
                                        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); // 通过Instant对象创建LocalDateTime对象
                                        bugs.setCreateTime(localDateTime);//提报日期
                                    }catch (Exception e){
                                        e.printStackTrace();
                                        log.error("批量导入日期转换异常:"+e);
                                        return AjaxResult.error("第"+rowIndex+"行的提报日期格式有误,请检查提报日期输入格式是否正确");
                                    }
                                    break;
                                case 2:
                                    if(StringUtils.isEmpty(Bvalue)){
                                        return AjaxResult.error("第"+rowIndex+"行的问题描述不能为空");
                                    }
                                    bugs.setDescriptions(Bvalue);
                                    break;
                                case 3:
                                    if(StringUtils.isEmpty(Bvalue)){
                                        return AjaxResult.error("第"+rowIndex+"行的fw版本不能为空");
                                    }
                                    bugs.setBugVersion(Bvalue);
                                    break;
                                case 4:
                                    if(StringUtils.isEmpty(Bvalue)){
                                        return AjaxResult.error("第"+rowIndex+"行的提交人不能为空");
                                    }
                                    bugs.setCreateUserName(Bvalue);
                                    break;
                                case 5:
                                    if(StringUtils.isEmpty(Bvalue)){
                                        return AjaxResult.error("第"+rowIndex+"行的问题等级不能为空");
                                    }
                                    bugs.setLevel(Bvalue);
                                    break;
                                case 6:
                                    if(StringUtils.isEmpty(Bvalue)){
                                        return AjaxResult.error("第"+rowIndex+"行的不良率不能为空");
                                    }
                                    bugs.setBadPersentage(Bvalue);
                                    break;
                                case 7:
                                    if(StringUtils.isEmpty(Bvalue)){
                                        return AjaxResult.error("第"+rowIndex+"行的原因分析不能为空");
                                    }
                                    bugs.setAnalysis(Bvalue);
                                    break;
                                case 8:
                                    if(StringUtils.isEmpty(Bvalue)){
                                        return AjaxResult.error("第"+rowIndex+"行的改善对策不能为空");
                                    }
                                    bugs.setAnswer(Bvalue);
                                    break;
                                case 9:
                                    if(StringUtils.isEmpty(Bvalue)){
                                        return AjaxResult.error("第"+rowIndex+"行的责任人不能为空");
                                    }
                                    bugs.setRespon(Bvalue);
                                    break;
                                case 10:
                                    if(StringUtils.isEmpty(Bvalue)){
                                        return AjaxResult.error("第"+rowIndex+"行的改善时间不能为空");
                                    }
                                    try {
                                        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
                                        Date dlDate = dateFormat.parse(Bvalue);
                                        Instant instant = dlDate.toInstant(); // 将Date对象转换为Instant对象
                                        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); // 通过Instant对象创建LocalDateTime对象
                                        bugs.setUpdateTime(localDateTime);//改善日期
                                    }catch (Exception e){
                                        e.printStackTrace();
                                        log.error("批量导入bug数据日期转换异常:"+e);
                                        return AjaxResult.error("第"+rowIndex+"行的改善时间格式有误,请检查改善时间输入格式是否正确");
                                    }
                                    break;
                                case 11:
                                    if(StringUtils.isEmpty(Bvalue)){
                                        return AjaxResult.error("第"+rowIndex+"行的close fw版本不能为空");
                                    }
                                    bugs.setCloseVersion(Bvalue);
                                    break;
                                case 12:
                                    if(StringUtils.isEmpty(Bvalue)){
                                        return AjaxResult.error("第"+rowIndex+"行的bug状态不能为空");
                                    }
                                    bugs.setBugStatusTxt(Bvalue);
                                    break;
                                default:
                                    break;
                            }

                        }
                        //读取完一行之后添加进List
                        list.add(bugs);
                        //读取完跳行
                        rowIndex++;
                    }else {
                        //有可能是bug的问题类别为空，判断一下其他字段是否都为空
                        boolean empty=false;
                        for (int i = 1; i < 12; i++) {
                            String value = sheet.getRow(rowIndex).getCell(i).toString();
                            if(!StringUtils.isEmpty(value)){//有一个不为空就证明不是空
                                empty=false;
                            }else {//否则是空
                                empty=true;
                            }
                        }
                        if(empty){
                            rowIndex++;//跳过
                            if(rowIndex==10000){
                                flag=false;
                                break;
                            }
                        }else {
                            //TODO for循环 读取这一行的bug数据
                            Bugs bugs = new Bugs();
                            for (int i = 0; i < 13; i++) {
                                String Bvalue = sheet.getRow(rowIndex).getCell(i).toString();
                                switch (i){
                                    case 0:
                                        if(StringUtils.isEmpty(Bvalue)){
                                            return AjaxResult.error("第"+rowIndex+"行的问题类别不能为空");
                                        }
                                        bugs.setProblemType(Bvalue);
                                        break;
                                    case 1:
                                        if(StringUtils.isEmpty(Bvalue)){
                                            return AjaxResult.error("第"+rowIndex+"行的提报日期不能为空");
                                        }
                                        try {
                                            SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
                                            Date dlDate = dateFormat.parse(Bvalue);
                                            Instant instant = dlDate.toInstant(); // 将Date对象转换为Instant对象
                                            LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); // 通过Instant对象创建LocalDateTime对象
                                            bugs.setCreateTime(localDateTime);//提报日期
                                        }catch (Exception e){
                                            e.printStackTrace();
                                            log.error("批量导入日期转换异常:"+e);
                                            return AjaxResult.error("第"+rowIndex+"行的提报日期格式有误,请检查提报日期输入格式是否正确");
                                        }
                                        break;
                                    case 2:
                                        if(StringUtils.isEmpty(Bvalue)){
                                            return AjaxResult.error("第"+rowIndex+"行的问题描述不能为空");
                                        }
                                        bugs.setDescriptions(Bvalue);
                                        break;
                                    case 3:
                                        if(StringUtils.isEmpty(Bvalue)){
                                            return AjaxResult.error("第"+rowIndex+"行的fw版本不能为空");
                                        }
                                        bugs.setBugVersion(Bvalue);
                                        break;
                                    case 4:
                                        if(StringUtils.isEmpty(Bvalue)){
                                            return AjaxResult.error("第"+rowIndex+"行的提交人不能为空");
                                        }
                                        bugs.setCreateUserName(Bvalue);
                                        break;
                                    case 5:
                                        if(StringUtils.isEmpty(Bvalue)){
                                            return AjaxResult.error("第"+rowIndex+"行的问题等级不能为空");
                                        }
                                        bugs.setLevel(Bvalue);
                                        break;
                                    case 6:
                                        if(StringUtils.isEmpty(Bvalue)){
                                            return AjaxResult.error("第"+rowIndex+"行的不良率不能为空");
                                        }
                                        bugs.setBadPersentage(Bvalue);
                                        break;
                                    case 7:
                                        if(StringUtils.isEmpty(Bvalue)){
                                            return AjaxResult.error("第"+rowIndex+"行的原因分析不能为空");
                                        }
                                        bugs.setAnalysis(Bvalue);
                                        break;
                                    case 8:
                                        if(StringUtils.isEmpty(Bvalue)){
                                            return AjaxResult.error("第"+rowIndex+"行的改善对策不能为空");
                                        }
                                        bugs.setAnswer(Bvalue);
                                        break;
                                    case 9:
                                        if(StringUtils.isEmpty(Bvalue)){
                                            return AjaxResult.error("第"+rowIndex+"行的责任人不能为空");
                                        }
                                        bugs.setRespon(Bvalue);
                                        break;
                                    case 10:
                                        if(StringUtils.isEmpty(Bvalue)){
                                            return AjaxResult.error("第"+rowIndex+"行的改善时间不能为空");
                                        }
                                        try {
                                            SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
                                            Date dlDate = dateFormat.parse(Bvalue);
                                            Instant instant = dlDate.toInstant(); // 将Date对象转换为Instant对象
                                            LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); // 通过Instant对象创建LocalDateTime对象
                                            bugs.setUpdateTime(localDateTime);//改善日期
                                        }catch (Exception e){
                                            e.printStackTrace();
                                            log.error("批量导入bug数据日期转换异常:"+e);
                                            return AjaxResult.error("第"+rowIndex+"行的改善时间格式有误,请检查改善时间输入格式是否正确");
                                        }
                                        break;
                                    case 11:
                                        if(StringUtils.isEmpty(Bvalue)){
                                            return AjaxResult.error("第"+rowIndex+"行的close fw版本不能为空");
                                        }
                                        bugs.setCloseVersion(Bvalue);
                                        break;
                                    case 12:
                                        if(StringUtils.isEmpty(Bvalue)){
                                            return AjaxResult.error("第"+rowIndex+"行的bug状态不能为空");
                                        }
                                        bugs.setBugStatusTxt(Bvalue);
                                        break;
                                    default:
                                        break;
                                }

                            }
                            //读取完一行之后添加进List
                            list.add(bugs);
                            //读取完跳行
                            rowIndex++;
                        }
                    }
                }
            }
        }
        AjaxResult ajaxResult = projectService.batchAddProjectBugList(excelDate);
        if(ajaxResult.isSuccess()){
            //导入成功保存导入的excel数据
            new Thread(()->{
                sysFilesService.FileUploadTwo(file, FileType.IMPORT.getCode(),userId,"项目bugList导入文件");
            }).start();
        }
        return ajaxResult;
    }

    @PreAuthorize("@ss.hasPermi('business:project:open')")
    @Log(title = "项目管理:打开关闭项目",businessType = BusinessType.UPDATE)
    @GetMapping("/open/{id}")
    public AjaxResult openCloseProject(@PathVariable("id") Long id){
        return projectService.openProject(id);
    }

//    @Log(title = "项目管理:获取项目品牌及机型",businessType = BusinessType.OTHER)
    @GetMapping("/getBrand")
    public AjaxResult getProjectBrand(){
        return projectService.queryProjectBrand();
    }

    @GetMapping("/getCustom")
    public AjaxResult getCustom(){
        return projectService.queryProjectCustom();
    }

    /**
     * 获取bug问题类别数量统计
     * */
    @GetMapping("/getProblemTypeCount")
    public AjaxResult getProblemTypeCount(Project project){
        return projectService.getBugProblemTypeCount(project);
    }

    /**
     * 获取专案数量
     * */
    @GetMapping("/getSpecialCaseCount")
    public AjaxResult getSpecialCaseCount(){
        return projectService.findSpecialCaseCount();
    }

    /**
     * 板卡异常Top5
     * */
    @GetMapping("/getAdBoardTop5Count")
    public AjaxResult getAdBoardTop5Count(){
        return projectService.findAdBoardTop5Date();
    }

    /**
     * OC异常Top5
     * */
    @GetMapping("/getLcmOcTop5Count")
    public AjaxResult getLcmOcTop5Count(){
        return projectService.findLcmOcTop5Date();
    }

    /**
     * 电源异常Top5
     * */
    @GetMapping("/getPowerSupplyTop5Count")
    public AjaxResult getPowerSupplyTop5Count(){
        return projectService.findPowerSupplyTop5Date();
    }

    /**
     * 查询项目专案测试数据统计
     * */
    @GetMapping("/getProjectLevelTestCount")
    public AjaxResult getProjectLevelTestCount(Project project){
        return projectService.getProjectLevelTestDate(project);
    }

    /**
     * 获取项目的成熟度
     * */
    @GetMapping("/projectMaturity")
    public AjaxResult getProjectMaturity(Project project){
        return  projectService.findProjectMaturity(project);
    }

    /**
     * 验证项目是否是close状态
     * @param id
     * @return
     */
    @GetMapping("/ifClose/{id}")
    public AjaxResult checkPjIfClose(@PathVariable("id") Long id){
        return projectService.checkProjectIfClose(id);
    }
}

